import React, { useState } from 'react';
import { Button, Upload, message, } from "antd";
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';
import { apiSysBatchUpload } from '../../../services/common'
import DeleteConfirm from '../DeleteConfirm';
import _ from 'lodash';
import './index.scss';
import { resquestDetialAttachmentListFormat } from "../../../utils/commonUtil";


const RequestUploadItem = ({
  // 上传按钮文案
  btnText,
  // 附件类型
  acceptType,
  // 上传或删除更新
  uploadUpdateFn,
  // 是否disabled
  disabled,
  // fileList
  fileListData,
  // 最大上传数量
  maxCount = 20,
}) => {
  const { t } = useTranslation();
  // 已上传的文件列表
  const [fileList, setFileList] = useState(fileListData || []);
  // 每次新上传的文件
  const [appendFileList, setAppendFileList] = useState([]);
  // 已删除的文件列表
  const [deleteFileList, setDeleteFileList] = useState([]);
  const { TYPE, VERIFIED } = acceptType;
  const acceptText = TYPE?.join(',');
  const MAX_SIZE = 500; // MB

  const beforeUpload = (file, list) => {
    // 判断最后一个文件是否添加进来
    if (file?.uid === list?.[list?.length - 1]?.uid) {
      // 判断上传数量
      if (fileList?.length + list?.length > maxCount) {
        message.error(t('common.uploadTipsSum'));
        return false;
      };
      // 文件总大小
      let filesSize = 0;
      // 判断文件格式
      for (let fileItem of list) {
        const type = fileItem?.type || fileItem?.name?.split('.')?.pop()?.toLowerCase();
        filesSize += fileItem.size;
        const isValidType = VERIFIED?.includes(type);
        if (!isValidType && VERIFIED?.length !== 0) {
          message.error(t('common.uploadTips', { type: TYPE }));
          return false;
        };
      };
      console.log(filesSize);
      // 判断文件总大小 MB
      if (filesSize / 1024 / 1024 > MAX_SIZE) {
        message.error(t('common.uploadTipsSize'));
        return false;
      };
      setAppendFileList(list);
      return true;
    } else {
      return false;
    }
  };
  const customRequest = () => {
    console.log('122');
    const param = new FormData();
    appendFileList.map((file) => {
      param.append('files', file);
    });
    apiSysBatchUpload(param).then((res) => {
      if (res?.data) {
        const resFiles = resquestDetialAttachmentListFormat(res?.data?.data?.items);
        setFileList([...fileList, ...resFiles]);
        uploadUpdateFn({
          fileList: [...fileList, ...resFiles]?.map(item => {
            return {
              ..._.omit(item, ['uid', 'name', 'status', 'url'])
            }
          }),
          deleteFileList: deleteFileList?.map(item => {
            return {
              ..._.omit(item, ['uid', 'name', 'status', 'url'])
            }
          }),
        });
      };
    });
  };

  const removeChange = (file) => {
    DeleteConfirm({
      t,
      title: t('common.deleteFileMsg'),
      onOk () {
        const newFileList = [...fileList];
        let newDeleteFileList = [];
        // 已上传并关联request的数据被删除
        if (fileListData?.filter(item => item?.attachmentInfoId === file?.attachmentInfoId)?.length > 0) {
          newDeleteFileList = newFileList?.filter(item => item.attachmentInfoId === file.attachmentInfoId);
          setDeleteFileList([...deleteFileList, ...newDeleteFileList]);
        };
        _.remove(newFileList, (curr => curr.attachmentInfoId === file.attachmentInfoId));
        setFileList(newFileList);
        uploadUpdateFn({
          fileList: newFileList?.map(item => {
            return {
              ..._.omit(item, ['uid', 'name', 'status', 'url'])
            }
          }),
          deleteFileList: [...deleteFileList, ...newDeleteFileList]?.map(item => {
            return {
              ..._.omit(item, ['uid', 'name', 'status', 'url'])
            }
          }),
        });
      }
    });
  };

  return (
    <Upload
      className='upload-item-wrap'
      maxCount={maxCount}
      accept={acceptText}
      beforeUpload={beforeUpload}
      customRequest={customRequest}
      multiple
      fileList={fileList}
      disabled={disabled}
      onRemove={(e) => removeChange(e)}
    >
      <Button icon={<UploadOutlined />} disabled={disabled}>{btnText}</Button>
    </Upload>
  );
};

export default RequestUploadItem;
